package net.biancheng.framework.web.service;

import net.biancheng.common.constant.CommonConstant;
import net.biancheng.exception.ServiceException;
import net.biancheng.exception.UserException;
import net.biancheng.common.model.LoginUser;
import net.biancheng.common.utils.SecurityUtils;
import net.biancheng.model.RegisterBody;
import net.biancheng.bean.SysRole;
import net.biancheng.bean.SysUser;
import net.biancheng.service.ISysRoleService;
import net.biancheng.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * @author: lb
 * @date: 2023/8/7 11:26
 * @desc: 登录实现类
 **/
@Component
public class SysLoginService {

    @Autowired
    private JwtTokenService jwtTokenService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService sysRoleService;


    /**
     * 登录验证
     * @param username 账号
     * @param password 密码
     * @return
     */
    public String login(String username, String password){
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException){
                throw new UserException("用户不存在/密码错误");
            }else {
                throw new ServiceException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return jwtTokenService.createToken(loginUser);
    }


    /**
     * 注册
     */
    public String register(RegisterBody registerBody)
    {
        String message = "", username = registerBody.getUserName(), password = registerBody.getPassword(), phone = registerBody.getPhone();
        //定义一个sysUser对象
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setPhone(phone);
        if (StringUtils.isEmpty(username))
        {
            message = "用户名不能为空";
        }
        else if (StringUtils.isEmpty(password))
        {
            message = "用户密码不能为空";
        }
        else  if (CommonConstant.NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(sysUser))){
            message = "当前账号["+ username +"]已存在";
        }
        else  if (CommonConstant.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(sysUser))){
            message = "当前手机号["+ phone +"]已存在";
        }
        else
        {
            sysUser = new SysUser();
            BeanUtils.copyProperties(registerBody, sysUser);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));

            //判断是否选择角色
            if(StringUtils.isNotEmpty(registerBody.getRole())){
                SysRole sysRole = sysRoleService.selectSysRoleByRoleKey(registerBody.getRole());
                if (sysRole != null){
                    Long[] roleIds = new Long[]{sysRole.getId()};
                    sysUser.setRoleIds(roleIds);
                }
            }

            int rows = sysUserService.insertSysUser(sysUser);
            if (rows > 0)
            {
                message = "";
            }
            else
            {
                message = "注册失败,请联系系统管理人员";
            }
        }
        return message;
    }

}
